package smart.wallet;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.LocalActivityManager;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.Toast;
//import HomeScreen.R;
import smart.wallet.MenuTabs;
import smart.wallet.db.DBAdapter;
import smart.wallet.db.DBHelper;
import smart.wallet.model.AccountModel;


public class Home extends Activity {
	
	private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    public static long CURRENT_ACCOUNT_ID;
    EditText account_name;
    Dialog first_enter_dialog;
    
    private GestureDetector gestureDetector;
	ImageButton launchButton;
	DBAdapter db;
	Cursor accounts;
	AccountModel account_model;
	boolean account_created;
	long balance;
	
	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	
		setContentView(R.layout.home);
		
		db = new DBAdapter(this);

		db.open();

		accounts = db.fetchAllAccounts();
		
		if (accounts.getCount() == 0){
			db.createAccount("Marcelo");
			accounts = db.fetchAllAccounts();
		}
		
		TextView nome_conta = (TextView) findViewById(R.id.Page_Name);
		nome_conta.setText(nome_conta.getText().toString()+" - Conta Demo");
		
		Home.CURRENT_ACCOUNT_ID = accounts.getLong(accounts.getColumnIndexOrThrow(DBHelper.ACCOUNT_ID));
		
		gestureDetector = new GestureDetector(new MyGestureDetector());
        View mainview = (View) findViewById(R.id.home);
		
		launchButton = (ImageButton)findViewById(R.id.imageButton1);
		
		launchButton.setOnClickListener(new View.OnClickListener(){
			public void onClick(final View v) {
				v.setSelected(true);
				Handler handler = new Handler(); 
			    handler.postDelayed(new Runnable() { 
			         public void run() { 
			        	 v.setSelected(false);
			         } 
			    }, 250); 
				Intent intent = new Intent(Home.this, Register.class);
				startActivity(intent);       
			}	
		});
		
		mainview.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        });
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		adjustThermometerPicture();
	}
	
	private void adjustThermometerPicture(){
		balance = calculateBalance();
		TextView balance_text = (TextView) findViewById(R.id.balance_text);
		balance_text.setText("R$ "+String.valueOf(balance));
		
		ImageView thermometer = (ImageView) findViewById(R.id.imageView2);
		if (balance <= 200){
			thermometer.setImageResource(R.drawable.bad_thermometer);
		} else if (balance <= 500){
			thermometer.setImageResource(R.drawable.medium_thermometer);
		} else {
			thermometer.setImageResource(R.drawable.good_thermometer);
		}
		
	}

	private long calculateBalance(){
		
		Cursor credits = db.fetchSumEachCategory(Home.CURRENT_ACCOUNT_ID, DBHelper.CREDIT);
		Cursor debits = db.fetchSumEachCategory(Home.CURRENT_ACCOUNT_ID, DBHelper.DEBT);
		
		long credits_sum = 0;
		long debits_sum = 0;
		
		if (credits.getCount() > 0){
			do {
				credits_sum += credits.getLong(3);
			} while(credits.moveToNext());
		} else {
			credits_sum = 0;
		}
		
		if (debits.getCount() > 0){
			do {
				debits_sum += debits.getLong(3);
			} while(debits.moveToNext());
		} else {
			debits_sum = 0;
		}
		
		return balance = credits_sum - debits_sum;
	}
	
	class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        	
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
                return false;
            }
            
            // right to left swipe
            if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            		TabHost tabHost =  (TabHost) getParent().findViewById(android.R.id.tabhost);
            		tabHost.setCurrentTab(MenuTabs.ANALYSIS_SCREEN);  
    				Home.this.overridePendingTransition(
						R.anim.slide_in_right,
						R.anim.slide_out_left
    				);
    			// left to right swipe
            }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            	TabHost tabHost =  (TabHost) getParent().findViewById(android.R.id.tabhost);
        		tabHost.setCurrentTab(MenuTabs.CONFIG_SCREEN); 
    				Home.this.overridePendingTransition(
						R.anim.slide_in_left, 
						R.anim.slide_out_right
    				);
            }

            return false;
        }
        
        // It is necessary to return true from onDown for the onFling event to register
        @Override
        public boolean onDown(MotionEvent e) {
	        	return true;
        }

    }
}	


